package com.lw.lost.activity.admin

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.ManageReportAdapter
import com.lw.lost.databinding.ActivityReportManageBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.Report

class ReportManageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityReportManageBinding
    private lateinit var db: DBlost
    private lateinit var reportAdapter: ManageReportAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityReportManageBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "举报管理"

        db = DBlost(this)
        setupRecyclerView()
        loadReports()
    }

    private fun setupRecyclerView() {
        reportAdapter = ManageReportAdapter(
            onReportClick = { report ->
                showReportDetailDialog(report)
            },
            onActionClick = { report ->
                showActionDialog(report)
            }
        )

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = reportAdapter
            addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        }
    }

    private fun loadReports() {
        val cursor = db.reportDao.getReports()
        val reports = mutableListOf<Report>()

        cursor.use {
            while (it.moveToNext()) {
                reports.add(
                    Report(
                        reportId = it.getLong(it.getColumnIndexOrThrow("reportId")),
                        userId = it.getLong(it.getColumnIndexOrThrow("userId")),
                        targetId = it.getLong(it.getColumnIndexOrThrow("targetId")),
                        reporterName = it.getString(it.getColumnIndexOrThrow("reporterName")),
                        targetName = it.getString(it.getColumnIndexOrThrow("targetName")),
                        reason = it.getString(it.getColumnIndexOrThrow("reason")),
                        status = it.getInt(it.getColumnIndexOrThrow("status")),
                        reportTime = it.getLong(it.getColumnIndexOrThrow("reportTime"))
                    )
                )
            }
        }

        reportAdapter.submitList(reports)
        binding.tvEmpty.visibility = if (reports.isEmpty()) View.VISIBLE else View.GONE
        binding.recyclerView.visibility = if (reports.isEmpty()) View.GONE else View.VISIBLE
    }

    private fun updateUI(reports: List<Report>) {
        reportAdapter.submitList(reports)

        // 更新统计信息
        val pendingReports = reports.count { it.status == 0 }
        val processedReports = reports.count { it.status == 1 }
        binding.tvReportCount.text = "共 ${reports.size} 条举报（待处理: $pendingReports, 已处理: $processedReports）"

        // 更新空状态显示
        binding.tvEmpty.visibility = if (reports.isEmpty()) View.VISIBLE else View.GONE
        binding.recyclerView.visibility = if (reports.isEmpty()) View.GONE else View.VISIBLE
    }

    private fun showReportDetailDialog(report: Report) {
        // 获取被举报用户信息
        val userCursor = db.userDao.getUserById(report.userId)
        val username = if (userCursor.moveToFirst()) {
            "${userCursor.getString(userCursor.getColumnIndexOrThrow("name"))} (${userCursor.getString(userCursor.getColumnIndexOrThrow("username"))})"
        } else "未知用户"
        userCursor.close()

        AlertDialog.Builder(this)
            .setTitle("举报详情")
            .setMessage("""
                被举报用户：$username
                举报内容：${report.reason}
                举报时间：${report.reportTime}
                处理状态：${if (report.status == 0) "待处理" else "已处理"}
            """.trimIndent())
            .setPositiveButton("确定", null)
            .show()
    }

    private fun showActionDialog(report: Report) {
        if (report.status == 1) {
            Toast.makeText(this, "该举报已处理", Toast.LENGTH_SHORT).show()
            return
        }

        val items = arrayOf("封禁用户", "忽略举报")
        AlertDialog.Builder(this)
            .setTitle("处理举报")
            .setItems(items) { _, which ->
                when (which) {
                    0 -> showBanConfirmDialog(report)
                    1 -> ignoreReport(report.reportId)
                }
            }
            .show()
    }

    private fun showBanConfirmDialog(report: Report) {
        AlertDialog.Builder(this)
            .setTitle("确认封禁")
            .setMessage("确定要封禁该用户吗？封禁后该用户将无法登录系统。")
            .setPositiveButton("确定") { _, _ ->
                banUser(report.userId, report.reportId)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun banUser(userId: Long, reportId: Long) {
        val userResult = db.userDao.updateUserStatus(userId, 0)
        val reportResult = db.reportDao.updateStatus(reportId, 1)

        if (userResult > 0 && reportResult > 0) {
            Toast.makeText(this, "已封禁用户", Toast.LENGTH_SHORT).show()
            loadReports()
        } else {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun ignoreReport(reportId: Long) {
        val result = db.reportDao.updateStatus(reportId, 1)
        if (result > 0) {
            Toast.makeText(this, "已忽略举报", Toast.LENGTH_SHORT).show()
            loadReports()
        } else {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
} 